package com.aki.ai_property.service.impl;

import com.aki.ai_property.dao.LesseeDao;
import com.aki.ai_property.dto.SellLesseeDto;
import com.aki.ai_property.dto.LesseeExportDto;
import com.aki.ai_property.entity.Lessee;
import com.aki.ai_property.entity.Subscription;
import com.aki.ai_property.service.intf.LesseeService;
import com.aki.ai_property.util.StringUtil;
import com.aki.ai_property.vo.PageBean;

import com.aki.ai_property.vo.Result;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

import java.util.List;

/**
 * ━━━━━━永无BUG!━━━━━━
 *
 * @author AKI
 * @date 2022/8/27
 */
@Service
public class LesseeServiceImpl implements LesseeService {
    @Autowired
    private LesseeDao dao;

    @Override
    public Result save(Lessee lessee) {
        if(dao.save(lessee)>0){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }

    @Override
    public Result delete(Integer id) {
        if(dao.delete(id)>0){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }

    @Override
    public Result update(Lessee lessee) {
        if(dao.update(lessee)>0){
            return Result.ok();
        }else {
            return Result.fail();
        }

    }

    @Override
    public PageBean selectPage(String name, int page, int limit) {
        if(StringUtil.isNotEmpty(name)){
            name = "%"+name+"%";
        }
        int start =(page-1)*limit;
     return PageBean.ok(dao.selectCount(name),dao.selectPage(name,start,limit));
    }

    /** 查询全部 */
    @Override
    public Result all() {
        return Result.ok(dao.all());
    }

    /** 关联查询*/
    @Override
    public Result allDto() {
        return Result.ok(dao.allDto());
    }

    /**查询所有租户信息，用于导出*/
    @Override
    public List<LesseeExportDto> allLessee() {
        return dao.allLessee();
    }

    @Override
    public Result upload(MultipartFile file) throws IOException {
        //1.接收文件， 获取文件内容
        //1.验证上传文件是否存在
        if(!file.isEmpty()){
            //2.解析Excel -EasyExcel
            //2.解析Excel数据
            List<LesseeExportDto> list= EasyExcel.read(file.getInputStream(), LesseeExportDto.class, new ReadListener() {
                @Override
                public void invoke(Object o, AnalysisContext analysisContext) {}
                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {}
            }).sheet().doReadSync();
            //3.Mybatis 实现批量新增
            if(dao.saveBatch(list)>0){
                //4.返回
                return Result.ok();
            }
        }
        return Result.fail();
    }
}
